import { _decorator, Component, Collider2D, Contact2DType, IPhysics2DContact,director, BoxCollider2D, Vec3, Prefab, instantiate,Node, Label } from 'cc';
const { ccclass, property } = _decorator;
import { PlayerController } from './PlayerController';
import { createEnemy } from './createEnemy';
import { boss } from './boss';
import { Weapon } from './Weapon';
import { Fireball } from './Fireball';

// 从本地数据中读取玩家上轮最高得分数据，如果没有则默认0
// let lastScore = window.localStorage.getItem('lastScore') || 0;
// import { GameData } from './GameData';
// 从本地数据中读取玩家历史最高得分数据，如果没有则默认0
let HistoryScore = window.localStorage.getItem('HistoryScore') || 0;
@ccclass('buff')
export class buff extends Component {
    // 玩家属性节点，用于读取各种属性
    @property(PlayerController)
    private Player:PlayerController = null;
    // 创建敌人脚本节点
    @property(createEnemy)
    createEnemy:createEnemy = null;
    // 游戏数据节点
    // @property(GameData)
    // GameData:GameData = null;

    // 游戏获胜界面
    @property(Node)
    winNode:Node = null;
    // 敌人挂载节点
    @property(Node)
    enemyNode:Node = null;

    // 武器预制体
    @property(Prefab)
    weaponPrefab:Prefab = null;
    // 火球预制体
    @property(Prefab)
    fireballPrefab:Prefab = null;

    // 武器挂载节点
    @property(Node)
    weaponNode:Node = null;
    // 火球挂载节点
    @property(Node)
    fireballNode:Node = null;
    // buff节点
    @property(Node)
    buffNode:Node = null;
    // 经验文本
    @property(Label)
    experienceLabel:Label = null
    // 分数文本
    @property(Label)
    scoreLabel:Label = null
    // 历史最高得分文本
    @property(Label)
    historyScoreLabel:Label = null

    // 两个武器的转速buff节点
    @property(Node)
    weaponSpeed:Node = null;
    @property(Node)
    fireballSpeed:Node = null;
    // 百分比伤害buff节点
    @property(Node)
    percentNode:Node = null;
    // 火球的ex技能灼烧buff节点
    @property(Node)
    burningNode:Node = null;

    // 火球增加攻击力buff节点
    @property(Node)
    fireballAttack:Node = null;

    // 击败敌人获得经验,累积一定经验可以升级选择buff
    public experience = 0
    // 当前得分数
    public score:number = 0
    // 玩家已选择buff数量
    public buffNums = 0
    // 玩家可选择的Buff库;
    private buffs = [];

    // 灼烧技能buff在buffs内的下标
    private burningIndex = 0
    // 升级所需经验倍率
    public experienceRate = 1
    
    protected onLoad(): void {
        this.buffs.push(this.buffNode.children[0])
        this.buffs.push(this.buffNode.children[1])
        this.buffs.push(this.buffNode.children[2])
        this.buffs.push(this.buffNode.children[3])
        this.buffs.push(this.buffNode.children[4])
        this.buffs.push(this.buffNode.children[5])
        this.buffs.push(this.buffNode.children[6])
        this.buffs.push(this.buffNode.children[7])
        this.buffs.push(this.percentNode)
        // 读取历史最高得分
        this.historyScoreLabel.string = HistoryScore.toString()
        // 每局开始时更新本轮得分数据
        // window.localStorage.setItem('lastScore', '0')
        // console.log(lastScore)
        console.log(this.buffs)
    }

    // 展示buff节点
    showBuff(){
        if(this.buffNode.active){// 在buff节点正在显示时，无法继续显示
            this.experience += 100
            return
        }
        this.buffNode.active = true
        // 暂停游戏
        director.pause()
        // 玩家属性
        let player = this.Player.getComponent(PlayerController)
        // 注销所有定时器
        this.createEnemy.getComponent(createEnemy).stopCreate()
        for(var i = 0;i<player.weaponNums;i++){
            clearInterval(this.weaponNode.children[i].getComponent(Weapon).weaponRunTimer)
        }
        for(var i = 0;i<player.fireballNums;i++){
            clearInterval(this.fireballNode.children[i].getComponent(Fireball).FireballRunTimer)
        }
        for(var i = 0;i<this.enemyNode.children.length;i++){
            // boss攻击定时器
            if(this.enemyNode.children[i].getComponent(boss)&&this.enemyNode.children[i].getComponent(boss).bossATKTimer){
                clearInterval(this.enemyNode.children[i].getComponent(boss).bossATKTimer)
            }
        }
        // console.log(this.buffs)
        while (true) {// 在buff库中随机选择三种buff展示
            let index1 = Math.floor(Math.random() * this.buffs.length)
            let index2 = Math.floor(Math.random() * this.buffs.length)
            let index3 = Math.floor(Math.random() * this.buffs.length)
            if (index1 != index2 && index2 != index3 && index1 != index3) {
                if(this.buffs[index1] && this.buffs[index2] && this.buffs[index3]){// 抽取的buff都存在时，展示buff
                    this.buffs[index1].setPosition(new Vec3(0, 100, 0))
                    this.buffs[index2].setPosition(new Vec3(0, 0, 0))
                    this.buffs[index3].setPosition(new Vec3(0, -100, 0))
                    this.buffs[index1].active = true
                    this.buffs[index2].active = true
                    this.buffs[index3].active = true
                    break
                }else{
                    continue
                }
            } else {
                continue
            }
        }
    }

    // buff
    // 武器伤害+5
    addATk1(){
        this.Player.getComponent(PlayerController).attack += 5
        // 恢复武器的定时转动
        this.reSetTimer()
        // 持有buff数量加1
        this.buffNums += 1
        this.buffNode.active = false
        this.resumeGame()// 恢复游戏运行
    }
    // 火球伤害+10%
    addATk2(){
        this.Player.getComponent(PlayerController).FireAttack *= 1.1
        Math.floor(this.Player.getComponent(PlayerController).FireAttack)
        // 恢复武器的定时转动
        this.reSetTimer()
        // 持有buff数量加1
        this.buffNums += 1
        this.buffNode.active = false
        this.resumeGame()// 恢复游戏运行
    }
    // 武器数量加1(最多十把武器)
    addWeapon(){
        // 制作武器预制体
        let weapon = instantiate(this.weaponPrefab)
        // 玩家属性
        let player = this.Player.getComponent(PlayerController)
        // 玩家持有武器数量加1
        player.weaponNums += 1
        if(player.weaponNums >= 10){
            // 销毁节点的同时在buff库内删除数据
            for(var i = 0;i<this.buffs.length;i++){
                if(this.buffs[i]._name == '增加一把武器'){
                    this.buffs.splice(i,1)
                }
            }
        }
        // 设置位置，挂载武器
        weapon.setPosition(0,0)
        this.weaponNode.addChild(weapon)
        // 第一把武器的旋转角度
        const firstAngles = this.weaponNode.children[0].eulerAngles.z
        for(var i = 0;i<player.weaponNums;i++){// 重新设置所有武器的角度，保证是大致对称位置
            this.weaponNode.children[i].eulerAngles = new Vec3(0, 0, firstAngles+(360/player.weaponNums)*i)
        }
        // 恢复武器的定时转动
        this.reSetTimer()
        // 持有buff数量加1
        this.buffNums += 1
        this.buffNode.active = false
        this.resumeGame()// 恢复游戏运行
    }
    // 增加武器转速
    addWeaponSpeed(){
        // 玩家属性
        let player = this.Player.getComponent(PlayerController)
        // 武器转速-=1
        this.Player.getComponent(PlayerController).rotateSpeed -= 1
        // 恢复武器的定时转动
        this.reSetTimer()
        // 当武器定时器转速间隔为5时，销毁节点(无法继续选择)
        if(this.Player.getComponent(PlayerController).rotateSpeed <= 7){
            this.weaponSpeed.destroy()
            // 销毁节点的同时在buff库内删除数据
            for(var i = 0;i<this.buffs.length;i++){
                if(this.buffs[i]._name == '增加武器转速'){
                    this.buffs.splice(i,1)
                }
            }
            // this.buffs.splice(3,1)
            // console.log(this.buffs,"weapon")
        }
        // 持有buff数量加1
        this.buffNums += 1
        this.buffNode.active = false
        this.resumeGame()// 恢复游戏运行
    }
    // 火球数量加1(最多15个)
    addFireball(){
        // 制作火球预制体
        let fireball = instantiate(this.fireballPrefab)
        // 玩家属性
        let player = this.Player.getComponent(PlayerController)
        // 玩家持有火球数量加1
        player.fireballNums += 1
        if(player.fireballNums >= 15){
            // 销毁节点的同时在buff库内删除数据
            for(var i = 0;i<this.buffs.length;i++){
                if(this.buffs[i]._name == '增加一个火球'){
                    this.buffs.splice(i,1)
                }
            }
        }
        // 设置位置，挂载火球
        fireball.setPosition(0,0)
        this.fireballNode.addChild(fireball)
        for(var i = 0;i<player.fireballNums;i++){// 重新设置所有火球的角度，保证是大致对称位置
            this.fireballNode.children[i].eulerAngles = new Vec3(0, 0, (360/player.fireballNums)*i)
        }
        // 如果首个火球解锁了ex技能所有火球都解锁
        if(this.burningIndex == 1){// 只有主动选择学习灼烧技能index才会为1，用于辨别是否学习了该技能
            for(var i = 0;i<this.fireballNode.children.length;i++){
                this.fireballNode.children[i].getComponent(Fireball).ex = "Burning"
            }
        }
        if(player.fireballNums==1){// 当火球数量为1时，解锁两个关于火球的buff
            // 1是攻击力，2是转速
            this.buffs.push(this.fireballAttack)
            this.buffs.push(this.fireballSpeed)
        }
        if(player.fireballNums==3){// 火球数量达到3时可以解锁ex技能灼烧
            this.buffs.push(this.burningNode)
        }
        // 恢复武器的定时转动
        this.reSetTimer()
        // 持有buff数量加1
        this.buffNums += 1
        this.buffNode.active = false
        this.resumeGame()// 恢复游戏运行
    }
    // 增加火球转速
    addFireballSpeed(){
        // 武器转速-=1
        this.Player.getComponent(PlayerController).FireRotateSpeed -= 10
        // 恢复武器的定时转动
        this.reSetTimer()
        // 当武器定时器转速间隔为5时，销毁节点(无法继续选择)
        if(this.Player.getComponent(PlayerController).FireRotateSpeed <= 50){
            this.fireballSpeed.destroy()
            // 销毁节点的同时在buff库内删除数据
            for(var i = 0;i<this.buffs.length;i++){
                if(this.buffs[i]._name == '增加火球转速'){
                    this.buffs.splice(i,1)
                }
            }
        }
        // 持有buff数量加1
        this.buffNums += 1
        this.buffNode.active = false
        this.resumeGame()// 恢复游戏运行
    }
    // 升级所需经验倍率+10%
    addExperienceRate(){
        this.experienceRate += 0.1
        // 恢复武器的定时转动
        this.reSetTimer()
        // 持有buff数量加1
        this.buffNums += 1
        this.buffNode.active = false
        this.resumeGame()// 恢复游戏运行
    }
    // 移动速度+20
    addMoveSpeed(){
        this.Player.getComponent(PlayerController).moveSpeed += 20
        // 恢复武器的定时转动
        this.reSetTimer()
        // 持有buff数量加1
        this.buffNums += 1
        this.buffNode.active = false
        this.resumeGame()// 恢复游戏运行
    }
    // 玩家血量恢复30
    addBlood30(){
        this.Player.getComponent(PlayerController).health += 30
        this.Player.getComponent(PlayerController).healthNode.children[1].getComponent(Label).string = this.Player.getComponent(PlayerController).health.toString()
        // 恢复武器的定时转动
        this.reSetTimer()
        // 持有buff数量加1
        this.buffNums += 1
        this.buffNode.active = false
        this.resumeGame()// 恢复游戏运行
    }
    // 玩家血量恢复50
    addBlood50(){
        this.Player.getComponent(PlayerController).health += 50
        this.Player.getComponent(PlayerController).healthNode.children[1].getComponent(Label).string = this.Player.getComponent(PlayerController).health.toString()
        // 恢复武器的定时转动
        this.reSetTimer()
        // 持有buff数量加1
        this.buffNums += 1
        this.buffNode.active = false
        this.resumeGame()// 恢复游戏运行
    }
    // 玩家武器攻击附带1%的百分比伤害(扣除怪物总血量的1%,可叠加,最多3%)
    getRealAttack(){
        this.Player.percent += 0.01
        if(this.Player.percent >= 0.03){// 最多3%
            this.percentNode.destroy()
            for(var i = 0;i<this.buffs.length;i++){
                if(this.buffs[i]._name == '武器获得百分比伤害'){
                    this.buffs.splice(i,1)
                }
            }
        }
        // 恢复武器的定时转动
        this.reSetTimer()
        // 持有buff数量加1
        this.buffNums += 1
        this.buffNode.active = false
        this.resumeGame()// 恢复游戏运行
    }
    // 获取解锁ex技能灼烧
    getBurning(){
        for(var i = 0;i<this.fireballNode.children.length;i++){
            this.fireballNode.children[i].getComponent(Fireball).ex = "Burning"
        }
        this.burningNode.destroy()
        // 销毁节点的同时在buff库内删除数据
        for(var i = 0;i<this.buffs.length;i++){
            if(this.buffs[i]._name == '火球解锁ex技能灼烧'){
                this.buffs.splice(i,1)
            }
        }
        // 将下标修改为1，表示已经学习了灼烧技能
        this.burningIndex = 1
        // 恢复武器的定时转动
        this.reSetTimer()
        // 持有buff数量加1
        this.buffNums += 1
        this.buffNode.active = false
        this.resumeGame()// 恢复游戏运行
    }

    // 恢复所有武器的定时转动
    reSetTimer(){
        // 玩家属性
        let player = this.Player.getComponent(PlayerController)
        for(var i = 0;i<player.weaponNums;i++){// 恢复武器转动
            this.weaponNode.children[i].getComponent(Weapon).weaponRotate()
        }
        for(var i = 0;i<player.fireballNums;i++){// 恢复火球的转动
            this.fireballNode.children[i].getComponent(Fireball).FireballRotate()
        }
        for(var i = 0;i<this.enemyNode.children.length;i++){
            // boss攻击定时器
            if(this.enemyNode.children[i].getComponent(boss)&&this.enemyNode.children[i].getComponent(boss)){
                this.enemyNode.children[i].getComponent(boss).bossAttack()
            }
        }
    }
    // 恢复游戏运行
    resumeGame(){
        // 隐藏所有buff
        for(var i = 0;i<this.buffNode.children.length;i++){
            this.buffNode.children[i].active = false
        }
        // 开启游戏
        director.resume()
        // 注册敌人生成定时器
        this.createEnemy.getComponent(createEnemy).startCreate()
    }
    // 击杀敌人增加经验，攒到一定经验值可以升级，升级可以选择buff
    level(){
        // 如果boss已经出现，则无法继续增加经验
        // if(this.createEnemy.getComponent(createEnemy).isBoss)return
        // 每次击杀敌人随机获得1-10点经验,并随机在1-10上增加分数
        this.experience += Math.ceil(Math.random()*10*this.experienceRate)
        this.experienceLabel.string = this.experience.toString()
        // 修改得分
        this.score += Math.ceil(Math.random()*10)
        this.scoreLabel.string = this.score.toString()
        this.updateHistoryScore()
        
        if(this.experience >= 100){// 当经验值超过100时升级，经验减去100(升级所需)后展示buff选择面板
            this.experience -= 100
            this.experienceLabel.string = this.experience.toString()
            this.showBuff()
        }
    }
    // 更新历史最高得分
    updateHistoryScore(){
        if(this.score > Number(HistoryScore)){
            HistoryScore = this.score.toString()
            window.localStorage.setItem('HistoryScore', HistoryScore)
            this.historyScoreLabel.string = HistoryScore.toString()
        }
    }
    // 游戏结束，展示结算界面
    youWin(){
        if(this.createEnemy.getComponent(createEnemy).endless){// boss死亡，检测是否是无尽模式，是的话不展示结算界面，改为获得一个buff(经验+100)
            this.showBuff()
        }else{
            // 暂停游戏
            director.pause()
            // 玩家属性
            let player = this.Player.getComponent(PlayerController)
            // 注销所有定时器
            this.createEnemy.getComponent(createEnemy).stopCreate()
            for(var i = 0;i<player.weaponNums;i++){
                clearInterval(this.weaponNode.children[i].getComponent(Weapon).weaponRunTimer)
            }
            for(var i = 0;i<player.fireballNums;i++){
                clearInterval(this.fireballNode.children[i].getComponent(Fireball).FireballRunTimer)
            }
            // 展示youWin界面
            this.winNode.active = true
            this.winNode.children[1].children[1].getComponent(Label).string = this.score.toString()
        }
        
    }
}